package exercises.newcoder.solution;

/**
 * <a href="https://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47?tpId=188&&tqId=38627&rp=1&ru=/activity/oj&qru=/ta/job-code-high-week/question-ranking">
 *     NC55 最长公共前缀</a>
 * @author or2
 * @Description 给你一个长度为 nn 的字符串数组 strsstrs , 编写一个函数来查找字符串数组中的最长公共前缀，返回这个公共前缀。
 * @create 2021年08月31日 时间: 9:40
 */
public class LongestCommonPrefix {
    /**
     *
     * @param strs string字符串一维数组
     * @return string字符串
     */
    public String longestCommonPrefix (String[] strs) {
        if (strs.length == 0) {
            return "";
        }

        String first = strs[0];
//        最长公共字串长度
        int index = first.length();
        for (int i = 1; i < strs.length; i++) {
            index = Math.min(index, strs[i].length());
            for (int j = 0; j < index; j++) {
                if (strs[i].charAt(j) != first.charAt(j)) {
                    index = j;
                    break;
                }
            }
        }

        return first.substring(0, index);
    }

    public static void main(String[] args) {
        String[] strings = {"abca","abc","abca","abc","abcc"};
//        String[] strings = {"a","b"};
        LongestCommonPrefix longestCommonPrefix = new LongestCommonPrefix();
        System.out.println(longestCommonPrefix.longestCommonPrefix(strings));
    }
}